(function () {
    //从url获取到商品id
    function getUrl() {
        var param = location.search;
        return param.split("=")[1];
    }

    //渲染详情页
    function showItem(res) {
        let str = `<div class="littleArea"></div>
                    <li class="current"><img src=${res.img[0]} alt=""></li>
                    <li><img src=${res.img[1]} alt=""></li>
                    <li><img src=${res.img[2]} alt=""></li>
                    <li><img src=${res.img[3]} alt=""></li>
                    <li><img src=${res.img[4]} alt=""></li>`;
        let str2 = `<li class="current"><img class="bigImg" src=${res.img[5]}></li>
                    <li><img class="bigImg" src=${res.img[6]}></li>
                    <li><img class="bigImg" src=${res.img[7]}></li>
                    <li><img class="bigImg" src=${res.img[8]}></li>
                    <li><img class="bigImg" src=${res.img[9]}></li>`;
        let str3 = `
                        <li class="current"><img src=${res.img[10]} alt=""></li>
                        <li><img src=${res.img[11]} alt=""></li>
                        <li><img src=${res.img[12]} alt=""></li>
                        <li><img src=${res.img[13]} alt=""></li>
                        <li><img src=${res.img[14]} alt=""></li>`
        let goodname = `<em>${res.goodName}</em>`
        let price = `
                        <span><i style="font-size: 18px">¥</i>${res.price}</span>
                        <div><span>${res.discount}</span><span>¥${res.pre_price}</span></div>
                        <p class="priceBlock" style="clear:both;"><a style="color: #000;" href="#">评价(<span>${res.review.length}</span>)条　|</a>　梦芭莎自营
                        </p>`;
        let color = `<ul>
                              <li>颜色</li>
                              <li><a href="#"><img src=${res.img[15]} alt=""><span>${res.color}</span></a></li>
                        </ul>`;
        let size = `<li>尺码</li>`;
        $.each(res.size, function (key) {
            size += `<li><a href="javascript:;"><span>${key}</span></a></li>`;
        })
        $(".id").html(res.gid);
        $(".pic").html(str);
        $(".bigPic").html(str2);
        $(".list_pic").html(str2);
        $(".cont_info h2").html(goodname);
        $(".price").html(price);
        $(".color").html(color);
        $(".size ul").html(size);
        $("#surplus").html(res.size["M"]);
    }

    //放大镜
    let scope = function (index) {
        $(".bigPic").hide();
        //放大镜
        //css()方法获取到的是字符串类型的值,因此要转换为数值类型,可更改为height(),是获取到数值类型
        let $width = parseInt($(".pic").width() / $(".bigImg").width() * $(".bigPic").width());
        let $height = parseInt($(".pic").height() / $(".bigImg").height() * $(".bigPic").height());
        //设置小区域的高度
        $(".pic").mouseenter(function () {
            $(".bigPic").css("display", "block");
            $(".littleArea").css({
                "width": $width,
                "height": $height
            }).show();
        }).mouseleave(function () {
            $(".littleArea").hide();
            $(".bigPic").hide();
        });
        $(".littleArea").mousemove(function (e) {
            let disX = e.clientX - $(".pic").offset().left - $(".littleArea").width() / 2;
            let disY = e.clientY - ($(".pic").offset().top - $(document).scrollTop()) - $(".littleArea").width() / 2;
            if (disY <= 0) {
                disY = 0;
            }
            if (disX <= 0) {
                disX = 0;
            }
            let maxW = $(".pic")[0].offsetWidth - $(".littleArea")[0].offsetWidth;
            let maxH = $(".pic")[0].offsetHeight - $(".littleArea")[0].offsetHeight;
            if (disX >= maxW) {
                disX = maxW
            }
            if (disY >= maxH) {
                disY = maxH
            }
            $(".littleArea").css({
                "left": disX,
                "top": disY
            }).parent().siblings(".bigPic").show().find(".bigImg ").css({
                "left": -(disX * 4),
                "top": -(disY * 4),
            })
        })
    }
    //加入购物车
    let addCart = function () {
        let user = JSON.parse(sessionStorage.getItem("userInfo"));
        //登录后,就把cookie里的商品加入数据库
        if (sessionStorage.getItem("userInfo") && $.cookie("carts")) {
            JSON.parse($.cookie("carts")).forEach((ele, index) => {
                let preObj = ele;
                preObj.uid = user.id;
                preObj.total = preObj.num * preObj.price;
                console.log(preObj);
                $.ajax({
                    url: "../../server/cart/addCart.php",
                    data: preObj,
                    type: "post"
                }).then(function (res) {
                    console.log(res);
                    //删除cookie
                    $.cookie("carts", "", {expires: -1});
                })
            });
        }
        $(".addCart").on("click", "#add", function () {
            let currentObj = JSON.parse($("#add").attr("data-info"));
            //如果没有登录,将商品存cookie里去
            if (sessionStorage.getItem("userInfo") == null) {
                let cookieList = JSON.parse($.cookie("carts") || '[]');
                console.log(cookieList);
                let flag = cookieList.some((ele, index) => {
                    if (ele.gid == currentObj.gid && ele.size == currentObj.size) {
                        console.log(ele);
                        cookieList[index].num = Number(cookieList[index].num) + 1;
                        return true;
                    } else {
                        return false;
                    }
                });
                if (flag != true) {
                    currentObj.img = currentObj.img[15];
                    currentObj.num = parseInt($("#good_num").html());//购买的数量
                    currentObj.size = $(".size .current a span").html();
                    currentObj.price = parseInt(currentObj.price);
                    currentObj.totalprice = currentObj.num * currentObj.price;
                    cookieList.push(currentObj);
                }
                $.cookie("carts", JSON.stringify(cookieList));
                alert("添加购物车成功");
            } else {

                //2. 如果登录,直接把数据保存数据的cart表
                currentObj.uid = user.id;
                currentObj.img = currentObj.img[15];
                currentObj.num = parseInt($("#good_num").html());//购买的数量
                currentObj.size =  $(".size .current a span").html();
                currentObj.price = parseInt(currentObj.price);
                currentObj.total = currentObj.num * currentObj.price;
                $.ajax({
                    url: "../../server/cart/addCart.php",
                    data: currentObj,
                    type: "post"
                }).then(function (res) {
                    console.log(res);
                    alert("添加购物车成功");
                })
            }
        })
    }
    let topAction = function () {
        $(".header_right").find("li").on("mouseenter", function () {
            $(this).children("img").css("display", "block");
        })
        $(".header_right").find("li").on("mouseleave", function () {
            $(this).children("img").css("display", "none");
        })
    }
    let CodeBuy = function () {
        $(document).on("click", "#img_code", function () {
            $("#img_code").css("display", "none").next().slideDown(1000);
        })

        $(document).on("click", "#close", function () {
            console.log(111);
            $(this).parent().css("display", "none");
            $("#img_code").css("display", "block");
        })
    }
    $(function () {
        $.ajax({
            url: "../../server/product/getGoodById.php",
            data: {"gid": getUrl()},
        }).then(function (res) {
            showItem(res);
            $("#add").attr("data-info", JSON.stringify(res));
        }).then(function () {
            //商品图片的轮播图
            $(".list_pic li").on("mouseenter", function () {
                let index = $(this).index();
                $(".pic").children("li").eq(index).addClass("current").siblings("li").removeClass("current");
                $(".bigPic li").eq(index).addClass("current").siblings("li").removeClass("current");
                //放大镜
            })
           //给箭头添加事件监听
            $("#add_num").click(function () {
                $("#good_num").html(parseInt($("#good_num").html()) + 1);
            })
            $("#minus_num").click(function () {
                let num = parseInt($("#good_num").html())
                if (num <= 1) {
                    return;
                } else {
                    $("#good_num").html(num - 1);
                }
            });
            //选择尺码
            $(".size").find("li a").on("click", function (e) {
               $(e.target).parent("li").addClass("current").siblings("li").removeClass("current");

            })
            scope();
            //添加购物车
            addCart();
            topAction();
            CodeBuy();
        })
    })
})()